package com.cx.core.dict.validator;

import com.cx.core.common.util.SpringContextUtils;
import com.cx.core.dict.annotation.EnumValidation;
import com.cx.core.dict.service.DictService;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EnumValidator implements ConstraintValidator<EnumValidation, Object> {

    private DictService service;

    private EnumValidation enumValidation;

    @Override
    public void initialize(EnumValidation constraintAnnotation) {
        // 初始化代码，这里可以获取注解的属性值
        this.enumValidation = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        service = SpringContextUtils.getBean(DictService.class);
        if (value == null) {
            return true;
        }
        if(StringUtils.isEmpty(service.getValue(enumValidation.value(), value.toString()))){
            context.buildConstraintViolationWithTemplate("枚举值不对");
            return false;
        }else{
            return true;
        }
    }
}